package com.dh.service.impl;

import com.dh.core.config.Constant;
import com.dh.entity.UserGood;
import com.dh.entity.vo.UserGoodVo;
import com.dh.repository.UserGoodRepository;
import com.dh.service.UserGoodService;
import com.dh.service.UserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;

@Service
public class UserGoodServiceImpl implements UserGoodService {

    @Autowired
    private UserGoodRepository userGoodRepository;

    @Autowired
    private UserService userService;

    @Override
    public void create(UserGood userGood) {
        userGoodRepository.save(userGood);
    }

    @Override
    public Page<UserGoodVo> page(PageRequest pageRequest) {
        return userGoodRepository.findByDeleted(Constant.NOT_DELETE, pageRequest).map(g -> {
            UserGoodVo vo = new UserGoodVo();
            BeanUtils.copyProperties(g, vo);
            vo.setUser(userService.get(g.getUserId()));
            return vo;
        });
    }

    @Override
    public UserGood get(Long userGoodId) {
        return userGoodRepository.findOne(userGoodId);
    }

    @Override
    public void delete(Long userGoodId) {
//        UserGood good = userGoodRepository.findOne(userGoodId);
//        good.setDeleted(Constant.DELETE);
//        userGoodRepository.save(good);
        userGoodRepository.delete(userGoodId);
    }

    @Override
    public void update(UserGood userGood) {
        userGoodRepository.save(userGood);
    }

    @Override
    public UserGood findByNoAndDeleted(String no, byte deleted) {
        return userGoodRepository.findByNoAndDeleted(no,deleted);
    }

    @Override
    public void deleteByUserId(Long userId) {
        userGoodRepository.deleteByUserId(userId);
    }


}
